#pragma once
#include "../3rd/cpp-httplib/httplib.h"
#include "../3rd/rapidjson/include/rapidjson/document.h"
#include "utils/dbutils.hpp"
#include "utils/transutils.hpp"

using namespace httplib;
using namespace rapidjson;

class Chart_ {
 public:
  Chart_() {
    for (int i = 0; i < 5; ++i) {
      values[i] = std::vector<int>();
    }
  }

  std::vector<int> values[5];

  template <typename Writer>
  void Serialize(Writer& writer) const {
    const static std::vector<std::string> names = {
        "Protection", "Disinfection", "Drugs", "Diagnosis", "Others"};
    writer.StartObject();
    for (size_t i = 0; i < 5; ++i) {
      writer.String(names[i].c_str());
      writer.StartArray();
      for (const auto& v : values[i]) {
        writer.Int(v);
      }
      writer.EndArray();
    }
    writer.EndObject();
  }
};

void ChartReceipt(const Request& req, Response& res) {
  res.set_header("Access-Control-Allow-Origin", "*");

//   std::cout << req.body << std::endl;

  Document doc;
  doc.Parse(req.body.c_str());
  std::vector<std::string> types = {"防护类", "消毒类", "药品类", "诊断类",
                                    "其他"};
  Chart_ chart;
  for (size_t i = 0; i < doc.Size(); ++i) {
    auto date = doc[i].GetString();
    for (size_t j = 0; j < 5; ++j) {
      auto sql =
          "select count(*) from receipts where type = " + Qstring(types[j]) +
          " and donateTime = " + Qstring(date) + ";";
      auto result = DBWrapper::GetInstance()->Select(sql);
      chart.values[j].push_back(std::stoi(result->at(0).at(0)));
    }
  }
  res.set_content(Object2Json(chart), "application/json");
}

void ChartDistribution(const Request& req, Response& res) {
  res.set_header("Access-Control-Allow-Origin", "*");

//   std::cout << req.body << std::endl;

  Document doc;
  doc.Parse(req.body.c_str());
  std::vector<std::string> types = {"防护类", "消毒类", "药品类", "诊断类",
                                    "其他"};
  Chart_ chart;
  for (size_t i = 0; i < doc.Size(); ++i) {
    auto date = doc[i].GetString();
    for (size_t j = 0; j < 5; ++j) {
      auto sql =
          "select count(*) from distributions where type = " + Qstring(types[j]) +
          " and distributeTime = " + Qstring(date) + ";";
      auto result = DBWrapper::GetInstance()->Select(sql);
      chart.values[j].push_back(std::stoi(result->at(0).at(0)));
    }
  }
  res.set_content(Object2Json(chart), "application/json");
}
